var noticetime = 60;
var codetime = 60;
var baseurl = "https://bab.moreqifu.cn";
var resend = 1;
var restatic = 1;
var resubmit = 1;
var clicksubmit = 1;
var site = {};
var siteinfo = "";
var siteBackLists = {};
var urlParams = {};
var urlParamsStatus = false;
var submit_register = 1;
var request_params = {"clickid":"","adid":"","creativeid":"","creativetype":""};
var from_data = {"key":"","name":"","phone":"","code":"","privacy":false};
var current_time = Math.round(new Date().getTime()/1000).toString();
var back_platfrom = "N";
var record_id = "";
var browser = "other";
var kfid = "";

function pageRender() {
    var pathname = window.location.pathname;
    kfid = pathname.replace("/kf/","");
    if (kfid.length >= 10) {
        siteErrorNotice(1001,"链接错误提醒","当前链接错误,请检查链接是否正确!");
        return;
    }
    browser = getBrowser();
    documentReady();
}

function documentReady() {
    var ispc = checkIsPc();
    if (ispc) {
        pcShowUrlQrcode();
        return "";
    }
    getUrlParamLists();
    requestParams().then(function (v) {
        if (urlParams.hasOwnProperty("debug_sign")) {
            if (urlParams.debug_time <= current_time) {
                siteErrorNotice(1001,"落地页过期提醒","联调落地页链接有效期为1小时,请前往后台重新获取!");
                return;
            }
            var debug_sign = $.md5(kfid+urlParams.debug_time);
            if (debug_sign != urlParams.debug_sign) {
                siteErrorNotice(1001,"链接错误提醒","联调落地页链接错误,请确认获取的链接是否正确!");
                return;
            }
            // 清空缓存方便联调
            removeCache();
        }
        // 抖音预加载落地页,不处理;访问后会重新调取
        if (back_platfrom == "dy" && request_params.clickid == "__CLICKID__") {
            return;
        }
        // 存在统计记录,则不再统计
        var statisticTime = localStorage.getItem("statistic_time_"+kfid) || "";
        if (statisticTime == "") {
            usersStatistics();
        } else {
            if (redirect_type != 2) {
                wxkfRedirect();
            }
        }
    });
    copyrightShow();
}

function removeCache() {
    localStorage.removeItem("statistic_time_"+kfid);
    localStorage.removeItem("urlscheme_time_"+kfid);
    localStorage.removeItem("record_id_"+kfid);
    // 表单提交事件回传
    localStorage.removeItem("submit_simple_"+kfid);
    localStorage.removeItem("submit_register_"+kfid);
}

function showPage() {
    if (redirect_type == 3) {
        $("#site-contain").hide();
    } else {
        $("#site-contain").show();
    }
}

function getBrowser() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.search('jssdk') != -1 || userAgent.search('aweme') != -1 || userAgent.search('bytelocale') != -1 || userAgent.search('bytedancewebview') != -1) {
        return "douyin";
    } else if (userAgent.search('baiduboxapp') != -1) {
        return "baidu";
    } else if (userAgent.search('kwai') != -1) {
        return "kuaishou";
    } else {
        return "other";
    }
}

function getUrlParamLists() {
    var search = window.location.search;
    query = search.replace("?","");
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        urlParams[pair[0]] = pair[1];
        if (i == (vars.length-1)) {
            urlParamsStatus = true;
        }
    }
}

function siteErrorNotice(code,title,message) {
    $(".site-contain").html('<div class="page"><div class="weui-msg"><div class="weui-msg__icon-area"><i class="weui-icon-warn weui-icon_msg-primary"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title">'+title+'</h2><p class="weui-msg__desc">'+message+'</p></div></div></div>');
}

function setReturnLink() {
    $(".site-contain a").each(function(){
        var url = $(this).attr("href");
        if (url.indexOf("?") != -1) {
            url = url+"&clickid="+request_params.clickid+"&adid="+request_params.adid+"&creativetype="+request_params.creativetype+"&creativetype="+request_params.creativetype;
        } else {
            url = url+"?clickid="+request_params.clickid+"&adid="+request_params.adid+"&creativetype="+request_params.creativetype+"&creativetype="+request_params.creativetype;
        }
        $(this).attr("href",url);
    });
}

function showFrom(autoclose) {
    if (autoclose) {
        var countdown_time = $(".top-notice font").text();
        noticetime = parseInt(countdown_time.replace("S",""));
        $("#showRegisterFrom").show().delay(noticetime*1000).fadeOut();
        $(".top-notice").show();
        // 自动关闭倒计时
        noticeTimeDown();
    } else {
        $("#showRegisterFrom").show();
    }
}

function requestParams() {
    return new Promise((resolve1, reject1)=>{
        // 点击ID,每个广告唯一
        var p1 = new Promise((resolve, reject) => {
            var clickid = "";
            var adid = "";
            if (!urlParamsStatus) {
                setTimeout(function(){
                    back_platfrom = urlParams.back_platfrom || "";
                    if (urlParams.back_platfrom == "dy" || browser == "douyin") {
                        clickid = urlParams.hasOwnProperty('clickid') ? urlParams.clickid : "";
                        adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "dy";
                        }
                    } else if (urlParams.back_platfrom == "bd" || browser == "baidu") {
                        clickid = urlParams.hasOwnProperty('bd_vid') ? urlParams.bd_vid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "bd";
                        }
                    } else if (urlParams.back_platfrom == "ks" || browser == "kuaishou") {
                        clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                        adid = urlParams.hasOwnProperty('aid') ? urlParams.aid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "ks";
                        }
                    } else if (urlParams.back_platfrom == "bili") {
                        clickid = urlParams.trackid;
                        adid = urlParams.campaignid;
                    } else if (urlParams.back_platfrom == "zh") {
                        cburl = urlParams.cb;
                        url = decodeURIComponent(cburl);
                        clickid = getOtherUrlParam(url,"sessionId");
                    } else if (urlParams.back_platfrom == "xmly") {
                        clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                        adid = urlParams.hasOwnProperty('materialid') ? urlParams.materialid : "";
                    } else if (urlParams.back_platfrom == "gdt") {
                        clickid = urlParams.hasOwnProperty('gdt_vid') ? urlParams.gdt_vid : urlParams.qz_gdt;
                        adid = urlParams.hasOwnProperty('wx_aid') ? urlParams.wx_aid : "";
                    } else if (urlParams.back_platfrom == "oppo") {
                        clickid = urlParams.hasOwnProperty('tid') ? urlParams.tid : "";
                        adid = urlParams.hasOwnProperty('pageId') ? urlParams.pageId : "";
                    } else if (urlParams.back_platfrom == "vivo") {
                        clickid = urlParams.hasOwnProperty('requestid') ? urlParams.requestid : "";
                        adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                    }
                    resolve({"clickid":clickid,"adid":adid})
                }, 100);
            } else {
                back_platfrom = urlParams.back_platfrom || "";
                if (urlParams.back_platfrom == "dy" || browser == "douyin") {
                    clickid = urlParams.hasOwnProperty('clickid') ? urlParams.clickid : "";
                    adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                    if (typeof(back_platfrom) == "undefined" && clickid != "") {
                        back_platfrom = "dy";
                    }
                } else if (urlParams.back_platfrom == "bd" || browser == "baidu") {
                    clickid = urlParams.hasOwnProperty('bd_vid') ? urlParams.bd_vid : "";
                    if (typeof(back_platfrom) == "undefined" && clickid != "") {
                        back_platfrom = "bd";
                    }
                } else if (urlParams.back_platfrom == "ks" || browser == "kuaishou") {
                        clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                        adid = urlParams.hasOwnProperty('aid') ? urlParams.aid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "ks";
                        }
                } else if (urlParams.back_platfrom == "bili") {
                    clickid = urlParams.trackid;
                    adid = urlParams.campaignid;
                } else if (urlParams.back_platfrom == "zh") {
                    cburl = urlParams.cb;
                    url = decodeURIComponent(cburl);
                    clickid = getOtherUrlParam(url,"sessionId");
                } else if (urlParams.back_platfrom == "xmly") {
                    clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                    adid = urlParams.hasOwnProperty('materialid') ? urlParams.materialid : "";
                } else if (urlParams.back_platfrom == "gdt") {
                    clickid = urlParams.hasOwnProperty('gdt_vid') ? urlParams.gdt_vid : urlParams.qz_gdt;
                    adid = urlParams.hasOwnProperty('wx_aid') ? urlParams.wx_aid : "";
                } else if (urlParams.back_platfrom == "oppo") {
                    clickid = urlParams.hasOwnProperty('tid') ? urlParams.tid : "";
                    adid = urlParams.hasOwnProperty('pageId') ? urlParams.pageId : "";
                } else if (urlParams.back_platfrom == "vivo") {
                    clickid = urlParams.hasOwnProperty('requestid') ? urlParams.requestid : "";
                    adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                }
                resolve({"clickid":clickid,"adid":adid})
            }
        })
     
        Promise.all([p1]).then((result) => {
            request_params = result[0];
            resolve1(request_params);
        })
    });
}

function usersStatistics() {
    if (restatic == 2) return;
    restatic = 2;
    var reqdata = apiSafe(request_params.adid);
    reqdata.clickid = request_params.clickid;
    reqdata.adid = request_params.adid;
    reqdata.code = urlParams.code;
    reqdata.from = urlParams.from;
    reqdata.back_platfrom = back_platfrom;
    reqdata.kfid = kfid;
    reqdata.record_id = generateRecordId();
    var ttwlStatic = new wailianStaticMethod(baseurl+"/api/version/2/kefu/wxkf_stat",kfid,reqdata,true,false);  
    ttwlStatic.device();
}

function staticBack() {
    // 成功加粉回传
    if (redirect_type != 2) {
        wxkfRedirect();
    }
}

function redirectWeixin() {
    simpleSubmit();
}

//获取url中的参数
function getOtherUrlParam(url,name) {
    var query = url.split("?");
    if (query.length <= 1) return "";
    var vars = query[1].split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == name){return pair[1];}
    }
    return "";
}


function hideFrom() {
    resubmit = 1;
    $(".site-from-contain").hide();
}

function apiSafe(keywords) {
    var iv = Math.round(new Date().getTime()/1000).toString();
    var sign = $.md5("tt"+iv+kfid+iv+"wl");
    return {"iv":iv,"sign":sign}
}

function privacy() {
    window.location.href = baseurl+"/site_privacy/"+kfid;
}

function simpleSubmit() {
    if (clicksubmit == 1) {
        var record_id = generateRecordId();
        clicksubmit = 2;
        $.ajax({
            type: 'GET',
            url: baseurl+"/api/version/2/kefu/wxkf_click",
            data: {
                "kfid":kfid,
                "record_id":record_id,
            },
            success:function(res){
                // 返回成功才拉起跳转避免统计不到
                wxkfRedirect();
            },
            error:function(XMLHttpRequest, textStatus){}
        });
    } else {
        wxkfRedirect();
    }
}

function wxkfRedirect() {
    var record_id = generateRecordId();
    var link_url = localStorage.getItem("link_url_"+kfid) || "";
    if (link_url != "") {
        window.location.href = link_url;
    }
}

// div抖动效果元素,次数,距离,持续时间
function divshake(element,intShakes, intDistance, intDuration) {
    var jqNode = $(element);
    jqNode.css({ position: 'relative' });
    for (var x = 1; x <= intShakes; x++) {
        jqNode.animate({ left: (intDistance * -1) }, (((intDuration / intShakes) / 4)))
        .animate({ left: intDistance }, ((intDuration / intShakes) / 2))
        .animate({ left: 0 }, (((intDuration / intShakes) / 4)));
    }
}

function copyrightShow() {
    if(copyright == 2){
        $("#showCopyright").hide();
    }else{
        setTimeout(()=>{
            var seeHeight = window.innerHeight;
            var bodyheight = document.body.scrollHeight;
            if(bodyheight < seeHeight){
                $("#showCopyright").addClass('site-copyright-slide');
            }
            $("#showCopyright").show();
        },1000);
    }
}

function noticeTimeDown() {
    var countdown_times = $(".top-notice font").text();
    var countdown_time = parseInt(countdown_times.replace("S",""));
    if(noticetime==countdown_time){
        var time1 = setInterval(function(){
            if(noticetime==0){
                $(".top-notice font").html(noticetime+"S");
                noticetime = 120;
                clearInterval(time1);
            }else{
                $(".top-notice font").html(noticetime+"S");
                noticetime--;
            }
        }, 1000);
    }
}

function codeTimeDown(id) {
    if(codetime==60){
        var time1=setInterval(function(){
            if(codetime==0){
                $("#"+id).html("重新发送").removeClass("disable");
                codetime = 60;
                clearInterval(time1);
            }else{
                $("#"+id).html("重新发送("+codetime+"S)").addClass("disable");
                codetime--;
            }
        }, 1000);
    }
}

function checkIsPc() {
    var bodywidth = document.body.clientWidth;
    if (bodywidth >= 700) {
        return true;
    } else {
        return false;
    }
}

function isWeiXin(){
    var ua = navigator.userAgent.toLowerCase()
    var isWeixin = ua.match(/micromessenger/i) == 'micromessenger'
    return isWeixin;
}

function isBaidu(){
    var ua = navigator.userAgent.toLowerCase()
    var isBaidu = ua.match(/baiduboxapp/i) == 'baiduboxapp'
    return isBaidu;
}

function isWeibo() {
    var ua = navigator.userAgent;
    if(ua.indexOf('Weibo') > -1) {
        return true;
    } else {
        return false;
    }
}

function pcShowUrlQrcode() {
    var bodywidth = document.body.clientWidth;
    var left = bodywidth/2+260;
    $(".site-pc-qrcode").css("left",left+"px").show();
    $(".site-contain").css("box-shadow","0px 0px 10px #888888");
    $("#preview_qrcode").hide().html("");
    var url = window.location.href;
    var qrcode = new QRCode(document.getElementById("preview_qrcode"), {
        text: url,
        width: 150,
        height: 150,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
    $("#preview_qrcode").show();
}

function randomString(e) {  
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
    for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
}

function generateRecordId() {
    var storageRecordId = localStorage.getItem("record_id_"+kfid) || "";
    if (storageRecordId == "") {
        var tableId = (new Date().getMonth()+1) % 4;
        var vertify = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var sd = '';
        for (var i = 0; i < 6; i++) {
            var random = Math.floor(Math.random() * (vertify.length));
            sd += vertify[random];
        }
        record_id = tableId+$.md5(kfid+current_time+sd);
        localStorage.setItem("record_id_"+kfid,record_id);
    } else {
        record_id = storageRecordId;
    }
    return record_id;
}

function prompt(message, style, time) {
    if (style == "success") {
        var html = '<i class="iconfont icon-chenggong" style="color:#34c38f;"></i><font>'+message+'</font>';
    } else if (style == "danger") {
        var html = '<i class="iconfont icon-shibai" style="color:#f46a6a;"></i><font>'+message+'</font>';
    } else if (style == "warning") {
        var html = '<i class="iconfont icon-tanhao" style="color:#f1b44c;"></i><font>'+message+'</font>';
    } else {
        var html = '<i class="iconfont icon-bangzhu" style="color:#556ee6;"></i><font>'+message+'</font>';
    }
    time = (time === undefined) ? 1200 : time;
    $("#site_alert_contain").html('<div class="site-alert">'+html+'</div>');
    $("#site_alert_contain").slideDown().delay(time).slideUp();
}
